/**
 * ChatWindow 群组相关逻辑模块
 * 包含群组管理、创建、详情等功能
 */

import { ref, type Ref, type ComputedRef } from 'vue'
import { useQuasar } from 'quasar'
import { triggerRef } from 'vue'
import type { useChatStore } from '../stores/chat'

export interface GroupModuleDeps {
  $q: ReturnType<typeof useQuasar>
  chatStore: ReturnType<typeof useChatStore>
  currentTargetId: ComputedRef<string | null>
  targetType: ComputedRef<'User' | 'Group'>
  recentChatUsers: Ref<any[]>
  groupMemberCountCache: Ref<Map<string, { count: number; timestamp: number }>>
  currentGroupMemberCount: Ref<number | undefined>
  groupMembersCache: Ref<Map<string, { alias?: string; displayName?: string; name?: string }>>
  updateRecentChatUsers: () => Promise<void>
  selectGroup: (groupId: string, groupName?: string) => Promise<void>
  updateGroupMembersCache: (groupId: string, members: Array<{ member_id: string; alias?: string; displayName?: string; name?: string }>) => void
  // UI 相关状态（从 UI 模块传入）
  detailsTargetId: Ref<string | null>
  detailsTargetName: Ref<string>
  showDetailsDrawer: Ref<boolean>
  groupDrawerMembers: Ref<any[]>
  currentGroupDrawerDetails: Ref<any>
  isGroupOwner: Ref<boolean>
  groupChatRemark: Ref<string>
  currentChatId: ComputedRef<string | null>
  handleViewGroupMembers: (groupId: string) => Promise<void>
  // 添加成员对话框相关状态（从 UI 模块传入）
  showAddContactDialog: Ref<boolean>
  availableFriendsForAdd: Ref<Array<{ id: string; name: string; remark?: string; avatar?: string; file_name?: string }>>
}

/**
 * 创建群组相关功能
 */
export function useChatWindowGroup(deps: GroupModuleDeps) {
  const {
    $q,
    chatStore,
    currentTargetId,
    targetType,
    recentChatUsers,
    groupMemberCountCache,
    currentGroupMemberCount,
    groupMembersCache,
    updateRecentChatUsers,
    selectGroup,
    updateGroupMembersCache,
    detailsTargetId,
    detailsTargetName,
    showDetailsDrawer,
    groupDrawerMembers,
    currentGroupDrawerDetails,
    isGroupOwner,
    groupChatRemark,
    currentChatId,
    handleViewGroupMembers,
    showAddContactDialog,
    availableFriendsForAdd,
  } = deps

  // 对话框状态
  const showCreateGroupDialog = ref(false)
  const creatingGroup = ref(false)

  // 处理显示群组详情（从群组列表触发）
  const handleShowGroupDetailsFromList = async (group: { group_id: string; group_name: string; member_count?: number }) => {
    detailsTargetId.value = group.group_id
    detailsTargetName.value = group.group_name
    showDetailsDrawer.value = true
    // 传递原始名称，确保不会被API覆盖
    await loadGroupDrawerDetails(group.group_id, group.group_name)
  }

  // 加载群组抽屉详情
  const loadGroupDrawerDetails = async (groupId: string, originalName: string | null = null) => {
    console.log('loadGroupDrawerDetails - 开始加载:', { groupId, originalName })
    try {
      const { getGroup, getGroupMembers } = await import('../services/im-group')
      const { getUserAsync } = await import('../services/auth')
      
      // 标准化群组ID（确保以 group_ 开头，且只添加一次）
      // 移除所有重复的 group_ 前缀
      let normalized = groupId.trim()
      while (normalized.startsWith('group_')) {
        normalized = normalized.substring(6) // 移除 'group_' (6个字符)
      }
      const normalizedGroupId = `group_${normalized}`
      console.log('loadGroupDrawerDetails - 标准化后的群组ID:', normalizedGroupId)
      
      // 加载群组信息
      try {
        const groupInfo = await getGroup(normalizedGroupId)
        currentGroupDrawerDetails.value = groupInfo
        
        // 更新群组人数缓存和显示
        if (groupInfo.member_count !== undefined && groupInfo.member_count !== null && groupInfo.member_count > 0) {
          // 如果当前正在查看这个群组，更新显示的人数
          if (currentTargetId.value === normalizedGroupId && targetType.value === 'Group') {
            currentGroupMemberCount.value = groupInfo.member_count
          }
          // 更新缓存
          groupMemberCountCache.value.set(normalizedGroupId, {
            count: groupInfo.member_count,
            timestamp: Date.now()
          })
        }
        
        // 更新群组名称显示
        if (groupInfo.group_name && groupInfo.group_name.trim() && !groupInfo.group_name.startsWith('group_')) {
          if (!originalName || originalName.startsWith('group_')) {
            detailsTargetName.value = groupInfo.group_name
          }
        } else {
          console.warn('⚠️ API返回的群组名称无效:', groupInfo.group_name)
        }
      } catch (error: any) {
        console.warn('获取群组详情失败:', error)
        currentGroupDrawerDetails.value = {
          group_id: groupId,
          group_name: detailsTargetName.value,
        }
        // 如果获取失败，尝试从聊天列表中获取群组名称
        try {
          const { getUserChats } = await import('../services/im-chat')
          const chats = await getUserChats()
          const chat = chats.find(c => (c.chat_type === 2 && c.to_id === groupId) || c.chat_id === groupId)
          if (chat && (chat as any).name) {
            detailsTargetName.value = (chat as any).name
            currentGroupDrawerDetails.value.group_name = (chat as any).name
          }
        } catch (e: any) {
          console.warn('从聊天列表获取群组名称失败:', e)
        }
      }
      
      // 加载群成员列表
      try {
        console.log('loadGroupDrawerDetails - 开始获取群成员:', normalizedGroupId)
        const members = await getGroupMembers(normalizedGroupId, false)
        console.log('loadGroupDrawerDetails - 获取到的群成员数量:', members.length, members)
        
        // 获取每个成员的用户信息，显示username而不是openid
        const { getUser } = await import('../services/message')
        const membersWithUserInfo = await Promise.all(
          members.map(async (member) => {
            try {
              const userInfo = await getUser(member.member_id)
              return {
                ...member,
                displayName: userInfo?.name || member.alias || member.member_id,
              }
            } catch (e: any) {
              return {
                ...member,
                displayName: member.alias || member.member_id,
              }
            }
          })
        )
        
        groupDrawerMembers.value = membersWithUserInfo
        
        // 调试：输出成员数据
        console.log('loadGroupDrawerDetails - 群成员数据已加载:', {
          groupId: normalizedGroupId,
          memberCount: membersWithUserInfo.length,
          members: membersWithUserInfo.map(m => ({
            member_id: m.member_id,
            alias: m.alias,
            displayName: (m as any).displayName
          }))
        })
        
        // 更新群成员缓存（用于消息显示时查找alias）
        updateGroupMembersCache(normalizedGroupId, membersWithUserInfo.map(m => ({
          member_id: m.member_id,
          alias: m.alias,
          displayName: m.displayName,
          name: (m as any).displayName || m.alias || m.member_id,
        })))
        
        // 获取当前用户在群组中的角色
        const currentUser = await getUserAsync()
        if (currentUser) {
          const currentUserId = currentUser.open_id || (currentUser.snowflake_id ? String(currentUser.snowflake_id) : undefined) || String(currentUser.id)
          const myMember = members.find(m => m.member_id === currentUserId)
          isGroupOwner.value = myMember?.role === 1 || 
            (currentGroupDrawerDetails.value?.owner_id && 
             (String(currentGroupDrawerDetails.value.owner_id) === currentUserId ||
              String(currentGroupDrawerDetails.value.owner_id) === currentUser.id ||
              (currentUser.snowflake_id && String(currentGroupDrawerDetails.value.owner_id) === String(currentUser.snowflake_id))))
        }
      } catch (error: any) {
        console.error('获取群组成员列表失败:', error)
        groupDrawerMembers.value = []
        console.log('loadGroupDrawerDetails - 成员列表加载失败，已清空:', groupDrawerMembers.value)
      }
      
      // 加载群聊备注
      try {
        const { getUserChats } = await import('../services/im-chat')
        const chats = await getUserChats()
        const chat = chats.find(c => c.chat_id === currentChatId.value || (c.chat_type === 2 && c.to_id === groupId))
        if (chat && (chat as any).remark) {
          groupChatRemark.value = (chat as any).remark
        } else {
          groupChatRemark.value = ''
        }
      } catch (error: any) {
        console.warn('获取群聊备注失败:', error)
        groupChatRemark.value = ''
      }
    } catch (error) {
      console.error('加载群组抽屉详情失败:', error)
    }
  }

  // 处理添加群成员
  const handleAddGroupMember = async () => {
    // 不关闭抽屉，只显示添加成员的对话框
    if (!detailsTargetId.value || !currentChatId.value) {
      $q.notify({
        type: 'warning',
        message: '请先选择一个群组',
        position: 'top',
      })
      return
    }

    try {
      const { getFriends } = await import('../services/im-friendship')
      const { getUserAsync } = await import('../services/auth')
      const { getGroupMembers } = await import('../services/im-group')
      
      const currentUser = await getUserAsync()
      if (!currentUser) {
        throw new Error('无法获取当前用户信息')
      }
      const currentUserId = currentUser.open_id || (currentUser.snowflake_id ? String(currentUser.snowflake_id) : undefined) || String(currentUser.id)
      
      // 获取现有成员列表
      let existingMemberIds: string[] = []
      try {
        const members = await getGroupMembers(detailsTargetId.value, false)
        existingMemberIds = members.map(m => m.member_id)
      } catch (e) {
        existingMemberIds = [currentUserId, detailsTargetId.value]
      }
      
      // 获取好友列表
      const friends = await getFriends()
      const { getUser } = await import('../services/message')
      
      // 过滤出可添加的好友（不在群组中的好友）
      const availableFriends = await Promise.all(
        friends
          .filter(f => {
            const friendId = f.user?.open_id || f.to_id
            return !existingMemberIds.includes(friendId) && friendId !== currentUserId
          })
          .map(async (f) => {
            const friendId = f.user?.open_id || f.to_id
            try {
              const userInfo = await getUser(friendId)
              return {
                id: friendId,
                name: userInfo?.name || f.remark || friendId,
                remark: f.remark,
                avatar: userInfo?.avatar || f.user?.avatar,
                file_name: userInfo?.file_name || f.user?.file_name,
              }
            } catch (e) {
              return {
                id: friendId,
                name: f.remark || friendId,
                remark: f.remark,
                avatar: f.user?.avatar,
                file_name: f.user?.file_name,
              }
            }
          })
      )
      
      // 设置可添加的好友列表并显示对话框（不关闭抽屉）
      // 即使没有可添加的好友，也显示对话框（显示空列表）
      availableFriendsForAdd.value = availableFriends
      showAddContactDialog.value = true
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '加载好友列表失败',
        position: 'top',
      })
    }
  }

  // 处理查看群公告
  const handleViewGroupAnnouncement = () => {
    $q.notify({
      type: 'info',
      message: '群公告功能待实现',
      position: 'top',
    })
  }

  // 处理移除群成员
  const handleRemoveGroupMember = async (memberId: string) => {
    if (!detailsTargetId.value) return
    
    // 检查权限
    if (!isGroupOwner.value && !groupDrawerMembers.value.some((m: any) => m.role === 2)) {
      $q.notify({
        type: 'warning',
        message: '只有群主和管理员可以移除成员',
        position: 'top',
      })
      return
    }
    
    // 获取成员信息
    const member = groupDrawerMembers.value.find((m: any) => m.member_id === memberId)
    const memberName = (member as any)?.displayName || memberId
    
    $q.dialog({
      title: '确认移除',
      message: `确定要将 "${memberName}" 移出群聊吗？`,
      cancel: true,
      persistent: true,
    }).onOk(async () => {
      try {
        const { removeGroupMember } = await import('../services/im-group')
        
        await removeGroupMember(detailsTargetId.value!, memberId)
        
        $q.notify({
          type: 'positive',
          message: '已移除成员',
          position: 'top',
        })
        
        // 重新加载群成员列表
        await loadGroupDrawerDetails(detailsTargetId.value!)
        
        // 刷新最近聊天列表（成员数可能变化）
        await updateRecentChatUsers()
        
        // 如果当前正在查看这个群组，更新显示的人数
        if (currentTargetId.value === detailsTargetId.value && targetType.value === 'Group') {
          try {
            const { getGroup } = await import('../services/im-group')
            const groupInfo = await getGroup(detailsTargetId.value!)
            if (groupInfo && groupInfo.member_count !== undefined && groupInfo.member_count !== null) {
              currentGroupMemberCount.value = groupInfo.member_count
            }
          } catch (error) {
            console.warn('更新群组人数失败:', error)
          }
        }
      } catch (error: any) {
        $q.notify({
          type: 'negative',
          message: error.message || '移除成员失败',
          position: 'top',
        })
      }
    })
  }

  // 处理显示移除成员对话框（批量移除）
  const handleShowRemoveMemberDialog = () => {
    $q.notify({
      type: 'info',
      message: '点击成员头像上的移除按钮可以移除该成员',
      position: 'top',
    })
  }

  // 处理更新群组名称
  const handleUpdateGroupName = async (groupId: string, currentName: string) => {
    // 检查是否是群主
    if (!isGroupOwner.value) {
      $q.notify({
        type: 'warning',
        message: '只有群主可以修改群聊名称',
        position: 'top',
      })
      return
    }
    
    $q.dialog({
      title: '修改群聊名称',
      message: '请输入新的群聊名称',
      prompt: {
        model: currentName,
        type: 'text',
        placeholder: '群聊名称',
        isValid: (val: string) => val.trim().length > 0 && val.trim().length <= 50,
      },
      cancel: true,
      persistent: true,
    }).onOk(async (newName: string) => {
      if (!newName || newName.trim() === '') {
        $q.notify({
          type: 'warning',
          message: '群聊名称不能为空',
          position: 'top',
        })
        return
      }
      
      const trimmedName = newName.trim()
      if (trimmedName === currentName) {
        return
      }
      
      try {
        const { updateGroup } = await import('../services/im-group')
        
        await updateGroup(groupId, {
          group_name: trimmedName,
        })
        
        $q.notify({
          type: 'positive',
          message: '群聊名称已更新',
          position: 'top',
        })
        
        // 更新详情抽屉中的群组名称
        if (currentGroupDrawerDetails.value) {
          currentGroupDrawerDetails.value.group_name = trimmedName
        }
        detailsTargetName.value = trimmedName
        
        // 刷新最近聊天列表，更新群组名称显示
        await updateRecentChatUsers()
        
        // 刷新群组缓存
        const { loadGroupsFromCache, saveGroupsToCache } = await import('../services/im-group')
        const cachedGroups = await loadGroupsFromCache() || []
        const groupIndex = cachedGroups.findIndex(g => g.group_id === groupId)
        if (groupIndex >= 0) {
          cachedGroups[groupIndex].group_name = trimmedName
          await saveGroupsToCache(cachedGroups)
        }
      } catch (error: any) {
        $q.notify({
          type: 'negative',
          message: error.message || '更新群聊名称失败',
          position: 'top',
        })
      }
    })
  }

  // 处理更新群聊备注
  const handleUpdateGroupRemark = async (chatId: string, currentRemark: string | null) => {
    $q.dialog({
      title: '修改群聊备注',
      message: '请输入新的备注（留空则清除）',
      prompt: {
        model: currentRemark || '',
        type: 'text',
        placeholder: '群聊备注仅自己可见',
        isValid: (val: string) => val.trim().length <= 50,
      },
      cancel: true,
      persistent: true,
    }).onOk(async (newRemark: string) => {
      try {
        const { updateChatRemark } = await import('../services/im-chat')
        
        const trimmedRemark = newRemark.trim() || null
        
        await updateChatRemark(chatId, trimmedRemark)
        
        $q.notify({
          type: 'positive',
          message: trimmedRemark ? '备注已更新' : '备注已清除',
          position: 'top',
        })
        
        groupChatRemark.value = trimmedRemark || ''
        
        await updateRecentChatUsers()
      } catch (error: any) {
        $q.notify({
          type: 'negative',
          message: error.message || '更新备注失败',
          position: 'top',
        })
      }
    })
  }

  // 处理解散群组
  const handleDissolveGroup = async () => {
    if (!detailsTargetId.value) return
    
    $q.dialog({
      title: '确认解散',
      message: `确定要解散群聊 "${detailsTargetName.value}" 吗？解散后群组将被永久删除，所有成员都将被移除。此操作不可恢复。`,
      cancel: true,
      persistent: true,
    }).onOk(async () => {
      try {
        const { dissolveGroup } = await import('../services/im-group')
        
        await dissolveGroup(detailsTargetId.value!)
        
        $q.notify({
          type: 'positive',
          message: '群组已解散',
          position: 'top',
        })
        
        showDetailsDrawer.value = false
        
        chatStore.currentTargetId = null
        chatStore.targetType = 'User'
        
        await updateRecentChatUsers()
      } catch (error: any) {
        $q.notify({
          type: 'negative',
          message: error.message || '解散群组失败',
          position: 'top',
        })
      }
    })
  }

  // 处理退出群聊
  const handleLeaveGroup = async () => {
    if (!detailsTargetId.value) return
    
    $q.dialog({
      title: '确认退出',
      message: `确定要退出群聊 "${detailsTargetName.value}" 吗？退出后将无法接收该群聊的消息。`,
      cancel: true,
      persistent: true,
    }).onOk(async () => {
      try {
        const { removeGroupMember } = await import('../services/im-group')
        const { getUserAsync } = await import('../services/auth')
        
        const currentUser = await getUserAsync()
        if (!currentUser) {
          throw new Error('无法获取当前用户信息')
        }
        const currentUserId = currentUser.open_id || (currentUser.snowflake_id ? String(currentUser.snowflake_id) : undefined) || String(currentUser.id)
        if (!currentUserId) {
          throw new Error('无法获取当前用户ID')
        }
        
        await removeGroupMember(detailsTargetId.value!, currentUserId)
        
        $q.notify({
          type: 'positive',
          message: '已退出群聊',
          position: 'top',
        })
        
        showDetailsDrawer.value = false
        
        chatStore.currentTargetId = null
        chatStore.targetType = 'User'
        
        await updateRecentChatUsers()
      } catch (error: any) {
        $q.notify({
          type: 'negative',
          message: error.message || '退出群聊失败',
          position: 'top',
        })
      }
    })
  }

  // 处理创建群组（从最近列表触发）
  const handleCreateGroup = () => {
    showCreateGroupDialog.value = true
  }

  // 执行创建群组
  const doCreateGroup = async (members: Array<{ id: string; name: string }>) => {
    if (!members || members.length === 0) {
      $q.notify({
        type: 'warning',
        message: '请至少选择一个联系人',
        position: 'top',
      })
      return
    }

    creatingGroup.value = true
    try {
      const { createGroup, addGroupMember } = await import('../services/im-group')
      const groupId = `group_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      
      let groupName = '群聊'
      if (members.length > 0) {
        const totalCount = members.length + 1
        const maxDisplayNames = 3
        const displayNames = members.slice(0, maxDisplayNames).map(m => m.name)
        const nameList = displayNames.join('、')
        
        if (members.length <= maxDisplayNames) {
          groupName = `${nameList} (${totalCount})`
        } else {
          groupName = `${nameList}... (${totalCount})`
        }
      }
      
      await createGroup({
        group_id: groupId,
        group_name: groupName,
        group_type: 1,
        apply_join_type: 1,
        introduction: undefined,
      })
      
      let finalGroupId = groupId
      for (const member of members) {
        try {
          const resultGroupId = await addGroupMember(finalGroupId, {
            member_id: member.id,
            role: 0,
          })
          if (resultGroupId && resultGroupId !== finalGroupId) {
            finalGroupId = resultGroupId
          }
        } catch (error: any) {
          console.warn(`添加成员 ${member.id} 失败:`, error)
        }
      }
      
      try {
        const { getOrCreateChat } = await import('../services/im-chat')
        const chatId = `group_${finalGroupId}`
        await getOrCreateChat({
          chat_id: chatId,
          chat_type: 2,
          to_id: finalGroupId,
        })
      } catch (error: any) {
        console.warn('创建群组聊天记录失败:', error)
      }
      
      try {
        const { getGroup, saveGroupsToCache } = await import('../services/im-group')
        const groupInfo = await getGroup(finalGroupId)
        if (groupInfo) {
          const { loadGroupsFromCache } = await import('../services/im-group')
          const cachedGroups = await loadGroupsFromCache() || []
          const existingIndex = cachedGroups.findIndex(g => g.group_id === finalGroupId)
          if (existingIndex >= 0) {
            cachedGroups[existingIndex] = groupInfo
          } else {
            cachedGroups.push(groupInfo)
          }
          await saveGroupsToCache(cachedGroups)
        }
      } catch (error: any) {
        console.warn('更新群组缓存失败:', error)
      }
      
      $q.notify({
        type: 'positive',
        message: '群组创建成功',
        position: 'top',
      })
      
      showCreateGroupDialog.value = false
      
      await updateRecentChatUsers()
      
      if (finalGroupId) {
        selectGroup(finalGroupId)
      }
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '创建群组失败',
        position: 'top',
      })
    } finally {
      creatingGroup.value = false
    }
  }

  return {
    showCreateGroupDialog,
    creatingGroup,
    handleShowGroupDetailsFromList,
    loadGroupDrawerDetails,
    handleAddGroupMember,
    handleViewGroupAnnouncement,
    handleRemoveGroupMember,
    handleShowRemoveMemberDialog,
    handleUpdateGroupName,
    handleUpdateGroupRemark,
    handleDissolveGroup,
    handleLeaveGroup,
    handleCreateGroup,
    doCreateGroup,
  }
}

